﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Taxomatic.UnitTests
{
    public class Helper
    {
        private Helper()
        { }

        private static Helper _instance = null;

        #region Singleton Instance
        private static object lockObj = new object();
        public static Helper Instance
        {
            get
            {
                lock (lockObj)
                {
                    if (_instance == null)
                    {
                        _instance = new Helper();
                    }
                }
                return _instance;
            }
        }
        #endregion

        public ICredentials ActiveUser
        {
            get;
            set;
        }


        // Retired, use HttpPost
        public string HttpPost(string url, string data)
        {
            if (url.Equals(string.Empty))
            {
                throw new ArgumentException("Please supply a url first.");
            }
            System.Net.ServicePointManager.Expect100Continue = false;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            /* This is the user connecting to the SharePoint service */
            request.Credentials = ActiveUser;
            request.ProtocolVersion = HttpVersion.Version11;
            request.KeepAlive = false;
            request.Method = "POST";
            request.Timeout = 360000;
            request.Accept = "*/*";
            request.ContentType = "application/json";

            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
            request.ContentLength = byteData.Length;
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }

            string responseAsString = string.Empty;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                responseAsString = sr.ReadToEnd();
                stream.Close();
            }
            response.Close();
            return responseAsString;
        }

        // Retired - do not use
        private string HttpGet(string url, string data)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Credentials = ActiveUser;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();

            StreamReader sr = new StreamReader(stream);
            string webPage = sr.ReadToEnd();

            stream.Close();
            return webPage;
        }

        public string HttpResponse(string url, string data, string method)   
        {        
            var retVal = "";
            System.Net.ServicePointManager.Expect100Continue = false;
            WebClient wc = new WebClient();        
            //wc.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("maint:password")));        
            wc.Credentials = ActiveUser;
            //wc.Headers.Add("referer", @"http://sip.ligmarine.com/admin/config.php?type=tool&display=printextensions");        
            wc.Headers.Add("Content-Type", "application/json");        
            //retVal = Convert.ToBase64String(Encoding.ASCII.GetBytes("maint:password"));        
            //Console.Write("Resulting Request Headers: ");        
            //Console.WriteLine(wc.Headers.ToString());        
            byte[] byteArray = null;
            if (null != data && data != string.Empty)
            {
                byteArray = Encoding.ASCII.GetBytes(data);
            }
             // Upload the input string using the HTTP 1.0 POST method.        
             byte[] responseArray = wc.UploadData(url, method, byteArray);
            
            // Console.WriteLine("\nResponse received was {0}", );        
            retVal = Encoding.ASCII.GetString(responseArray);        
            return retVal;    
        }

        /// <summary>
        /// This cleans up JSON respones which are returned as 
        /// d: { ... }
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public string CleanJSONObject(string response)
        {
            /* Replace delimiters */
            response = response.Replace("\\", string.Empty);
            /* Get the internal data of the response, ie everything after the d: */
            response = response.Substring(response.IndexOf("{", 2), response.LastIndexOf("}") - response.IndexOf("{", 2) - 1);

            return response;
        }

        /// <summary>
        /// Returns the content of the POST buffer as string
        /// </summary>
        /// <returns></returns>
        //public static string FormBufferToString()
        //{
        //    HttpRequest Request = HttpContext.Current.Request;

        //    if (Request.TotalBytes > 0)
        //        return Encoding.Default.GetString(Request.BinaryRead(Request.TotalBytes));

        //    return string.Empty;
        //}
    }
}
